package org.example;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者与消费者问题 （ReentrantLock）
 * synchronized => ReentrantLock
 * wait => await
 * notify => signal
 */
public class ProducerConsumer02 {
    public static void main(String[] args) {
        Resource2 resource = new Resource2();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    resource.increment();
                } catch (InterruptedException e) {  //  如果当前线程不是此对象的监视器的所有者(如：线程没有锁住对象)。
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    resource.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    resource.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    resource.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}

// 等待 -》 业务 -》 通知
class Resource2 {
    private int product = 0;
    private final Lock lock = new ReentrantLock();
    private final Condition full = lock.newCondition();
    private final Condition empty = lock.newCondition();

    public void increment() throws InterruptedException {
        try {
            lock.lock();
            while (product != 0) {
                // 等待
                full.await();
            }
            this.product++;
            System.out.println(Thread.currentThread().getName() + "=>" + product);
            // 通知唤醒其他线程
            empty.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (product == 0) {
                // 等待
                empty.await();
            }
            this.product--;
            System.out.println(Thread.currentThread().getName() + "=>" + product);
            // 通知唤醒其他线程
            full.signalAll();
        } finally {
            lock.unlock();
        }
    }
}